import demoModules from "@/router/demoModules";
import DemoItemLayout from "@/components/DemoItemLayout.vue";
import DemoPageLayout from "@/components/DemoPageLayout.vue";
function createAsyncComponent(fileName) {
  const modules_path = `/src/demos/${fileName}.vue`;
  const component = demoModules[modules_path];
  const AsyncComponent = () => ({
    // 需要加载的组件 (应该是一个 `Promise` 对象)
    component: component(),
    // 异步组件加载时使用的组件
    loading: {
      template: "<div>loading...</div>",
    },
    error: {
      template: "<div>error</div>",
    },
    delay: 200,

    timeout: 3000,
  });
  return AsyncComponent;
}
/**
 * 创建demo组件
 * @param {object} options
 * @param {string} options.group
 * @param {string} options.comp
 * @param {string} options.demo
 * @returns vue组件
 */
const createDemoItem = (options) => {
  const { group, comp, demo } = options;
  const demoVueFileName = `${group}-${comp}-${demo}`;
  const codeTxtFileName = `${group}-${comp}-${demo}`;
  const dynamicComponent = createAsyncComponent(demoVueFileName);
  return {
    name: `demo-item-${demo}`,
    components: {
      DemoItemLayout,
      dynamicComponent,
    },
    render(h) {
      return h(DemoItemLayout, {
        props: {
          codeTxtFileName,
        },
        scopedSlots:{
          title: () => demo,
          default: () => h(dynamicComponent),
        }
      });
    },
  };
};

/**
 * 创建demo页面组件
 * @param {object} options
 * @param {string} options.group
 * @param {string} options.comp
 * @param {Array} options.demosOption
 * @returns vue组件
 */
function createDemoPageComponent(options) {
  const demoListComp = options.demosOption.map((opt) => {
    return createDemoItem(opt);
  });
  const { group, comp } = options;
  return {
    name: `demo-${group}`,
    components: {
      DemoPageLayout,
    },
    render(h) {
      
      return h(DemoPageLayout, {
        props: {
          mdFileName: `${group}-${comp}`,
        },
        scopedSlots:{
        title: () => group,
        default: () =>
          h(
            "div",
            demoListComp.map((item, index) => {
              return h(item, {
                key: index,
              });
            })
          ),
        }
      });
    },
  };
}

export default createDemoPageComponent;
